<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row>
        <el-col :span="14" :offset="5">
          <h2>发表文章</h2>
          <el-form ref="goods" :rules="rules" :model="articles" :label-position="direction" label-width="80px">
            <el-form-item label="文章标题(必填)" prop="name">
              <el-input v-model="articles.name"/>
            </el-form-item>
            <el-form-item label="预览图片(用于预览展示)">
              <el-upload
                :action="uploadPath"
                :show-file-list="false"
                :headers="headers"
                :on-success="uploadPicUrl"
                class="avatar-uploader"
                accept=".jpg,.jpeg,.png,.gif">
                <img v-if="headerUrl" :src="headerUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
            <el-form-item label="所属分类" prop="category">
              <el-cascader :options="newCategory" expand-trigger="hover" @change="handleCategoryChange"/>
            </el-form-item>

            <el-form-item label="正文内容(必填)" prop="detail">
              <editor :init="editorInitSimple" v-model="articles.detail"/>
            </el-form-item>
          </el-form>
          <div class="op-container" style="text-align: center">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handlePublish">发布</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      title="提示"
      width="30%">
      <span>请填写完整的内容，才可以发布</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createStorage, uploadPath } from '@/api/storage'
import { publishArticles } from '@/api/articles'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'GoodsCreate',
  components: { Editor },

  data() {
    return {
      dialogVisible: false,
      direction: 'top',
      headerUrl: '',
      uploadPath,
      newCategory: [
        {
          label: '维护知识',
          value: 0
        },
        {
          label: '健康知识',
          value: 1
        }
      ],
      articles: { name: '', detail: '', headerId: '' },
      rules: {
        name: [{ required: true, message: '文章名称不能为空', trigger: 'blur' }],
        detail: [{ required: true, message: '文章内容', trigger: 'blur' }],
        category: [{ required: true, message: '分类不能为空', trigger: 'blur' }]
      },

      editorInitSimple: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright blockquote undo redo', 'hr numlist link image charmap preview  insertdatetime media forecolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.init()
  },

  methods: {
    init: function() {
    },
    handleCategoryChange(value) {
      this.articles.categoryId = value[value.length - 1]
    },
    handleCancel: function() {
      this.$router.push({ path: '/resource/list' })
    },
    handlePublish: function() {
      if (this.articles.name === '' || this.articles.detail === '') {
        this.dialogVisible = true
        return
      }
      const finalArticle = {
        article: this.articles
      }
      console.log(finalArticle)
      publishArticles(finalArticle).then(response => {
        console.log(response.data)
        this.$notify.success({
          title: '成功',
          message: '创建成功'
        })
        this.$router.push({ path: '/resource/list' })
      }).catch(response => {
        MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
          confirmButtonText: '确定',
          type: 'error'
        })
      })
    },
    uploadPicUrl: function(response) {
      console.log(response.data)
      this.headerUrl = response.data.url
      this.articles.headerId = response.data.id
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }
  }
}
</script>

<style>
  .el-card {
    margin-bottom: 10px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .avatar-uploader .el-upload {
    width: 145px;
    height: 145px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>
